/**
 * @Description: 首页活动配置
 * @author ourslookAdmin
 * @date 2019-04-26 14:38:59
 */
import React, { Fragment } from 'react';
import Modal from 'drag-modal';
import {
  BackTop,
  Button,
  Card,
  Checkbox,
  Col,
  Divider,
  Form,
  Icon,
  Input,
  InputNumber,
  message,
  Radio,
  Row,
  Select,
  Spin,
  Switch,
  Tooltip,
  Upload,
} from 'antd/lib/index';

import InputColor from 'react-input-color';
import { formatMessage, FormattedMessage } from 'umi/locale';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '../../../components/ourslook/BaseForm';
import ETable from '../../../components/ourslook/ETable';
import { getWebPath } from '../../../utils/request';
import uiUtils, { hasPermission } from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';
import DefaultImage from '../../../components/ourslook/DefaultImage';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;
const isTrue = true;
const isFalse = false;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(() => ({}))
class HomeNavi extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => index + 1,
    },
    {
      title: '类型',
      dataIndex: 'type',
      width: 120,
      align: 'center',
      sorter: false,
      render: (value, record, index) =>
        value === 1 ? (
          <span>普通订单</span>
        ) : value === 5 ? (
          <span>拼团</span>
        ) : value === 12 ? (
          <span>免费试读</span>
        ) : value === 2 ? (
          <span>专题活动</span>
        ) : value === 3 ? (
          <span>推荐有礼</span>
        ) : value === 4 ? (
          <span>幸运大抽奖</span>
        ) : (
          '--'
        ),
    },
    { title: '名称', dataIndex: 'name', width: 120, align: 'center', sorter: false },
    { title: '标题', dataIndex: 'title', align: 'center', sorter: false },
    // {title: '描述', dataIndex: 'description', align: 'center', sorter: false},
    {
      title: '图标',
      dataIndex: 'icon',
      align: 'center',
      width: 120,
      sorter: false,
      render: record => <DefaultImage src={record} width="100" />,
    },
    {
      title: '是否启用',
      dataIndex: 'enable',
      width: 120,
      align: 'center',
      sorter: false,
      // render: (value, record, index) => (value === isTrue ? <span>启用</span> : <span>禁用</span>),
      render: (value, record, index) => (
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          checked={record.enable}
          onChange={value1 => {
            record.enable = value1 === true ? isTrue : isFalse;
            this.updateData(record);
          }}
        />
      ),
    },
    { title: '排序', dataIndex: 'sort', width: 120, align: 'center', sorter: true },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 150,
      align: 'center',
      sorter: true,
      fixed: 'right',
      key: 'create_time',
    },
    {
      title: '操作',
      dataIndex: '',
      width: 120,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.update();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />}>
              <Icon type="edit" />
            </Tooltip>
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.view();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />}>
              <Icon type="info" />
            </Tooltip>
          </a>
        </React.Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: HomeNavi.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
      loading: false,
      sourceList: [],
      typeList: [],
      type: '',
    };
  }

  // 筛选条件
  static getFormList = () => [
    {
      type: 'SELECT',
      field: 'type',
      label: '类型',
      placeholder: '类型',
      list: [],
    },
    {
      type: 'INPUT',
      field: 'name',
      label: '名称',
      placeholder: '名称',
    },
    {
      type: 'INPUT',
      field: 'title',
      label: '标题',
      placeholder: '标题',
    },
  ];

  componentDidMount() {
    this.requestList();
    this.getHomeList();
  }

  componentWillUnmount() {}

  getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };

  handleChange = info => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      this.getBase64(info.file.originFileObj, imageUrl =>
        this.setState({
          imageUrl,
          loading: false,
        })
      );
    }
  };

  updateData = busHomenavi => {
    const url = 'bushomenavi/update';
    // uiUtils.showConfirm(formatMessage({ id: '确定要操作此记录吗？' }), () => {
    requestPromise(getWebPath() + url, {
      method: 'POST',
      body: busHomenavi,
    }).then(res => {
      if (res && res.code === 0) {
        uiUtils.showMessage(
          formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
          'success'
        );
        this.setState({
          showList: 1,
        });
        this.requestList();
      }
    });
    // });
  };

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  getTypeList = value => {
    const theTypeList = this.state.typeList;
    for (let i = 0; i < theTypeList.length; i += 1) {
      if (theTypeList[i].id === value) {
        this.setState({ type: theTypeList[i].name });
      }
    }
    return this.state.type;
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({ id: 'ours.curd.list.create' }), //创建
      editModel: {
        type: '',
        enable: isTrue,
        bugColor: '#5e72e4',
      },
      showList: 2,
    });
  };

  update = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    selectedRows[0].sort = `${selectedRows[0].sort}`;
    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />,
      editModel: JSON.parse(JSON.stringify(selectedRows[0])),
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  view = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].id);
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-delete' }), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}bushomenavi/delete`, {
        method: 'POST',
        body: ids,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const busHomeNavi = Object.assign(
      this.state.editModel,
      this.editForm.props.form.getFieldsValue()
    );

    if (busHomeNavi.bugColor != null) {
      busHomeNavi.bugColor = busHomeNavi.bugColor.hex;
    }
    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url = busHomeNavi.id == null ? '/bushomenavi/save' : '/bushomenavi/update';
        //对象删除一个属性
        //delete busHomeNavi.xxxxPros;
        this.setState({
          editModelConfirmLoading: true,
        });
        requestPromise(getWebPath() + url, {
          method: 'POST',
          body: busHomeNavi,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            this.setState({
              showList: 1,
            });

            //新增重新置为第一页
            if (!busHomeNavi.id) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  getHomeList = () => {
    requestPromise(`${getWebPath('/api/constants?type=OrderPomotionType')}`, {
      method: 'GET',
    }).then(res => {
      if (res) {
        const orderRefundStatus = uiUtils.getOptionJsonObjToArr(res.OrderPomotionType);
        const newRefundsArr = [{ id: '', name: '请选择活动类型' }, ...orderRefundStatus];
        const { formList: formListNew } = this.state;
        const formItem = this.findFormListItemByField('type');
        const intNewRefundsArr = [];
        newRefundsArr.forEach(item => {
          if (item.id !== '') {
            intNewRefundsArr.push({ id: Number.parseFloat(item.id), name: item.name });
          }
        });
        this.setState({ typeList: intNewRefundsArr });
        formItem.list = newRefundsArr;
        this.setState({
          formList: formListNew,
          sourceList: newRefundsArr,
        });
      }
    });
  };

  getInfo = id => {
    this.setState({
      editModelConfirmLoading: true,
    });
    requestPromise(getWebPath(`bushomenavi/info/${id}`), {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          editModel: res.busHomeNavi,
        });
      }
      this.setState({
        editModelConfirmLoading: false,
      });
    });
  };

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  operateByIds = status => {};

  //========其他所有的处理方法，请在按照约定进行处理==========

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    this.setState({ list: null });
    requestLists(this, `${getWebPath()}bushomenavi/list`, this.params);
  };

  vShow = showListNum => ({ display: this.state.showList === showListNum ? 'block' : 'none' });

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{ ...this.vShow(1) }}
          className={styles.oursCard}
          bodyStyle={{ padding: '20px' }}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('bushomenavi:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增" />
            </Button>

            <Button
              type="danger"
              icon="delete"
              {...style}
              onClick={this.del}
              hidden={!hasPermission('bushomenavi:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="id"
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              selectedIndexs={this.state.selectedIndexs}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{ x: 1200 }}
            />
          </div>
        </Card>

        <BackTop />

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
          this.state.showList === 1 ? null : (
            <Card
              title={this.state.editModalTitle}
              bordered={false}
              actions={[
                <div>
                  <React.Fragment>
                    <Button
                      type="primary"
                      hidden={this.state.editModalType === 'view'}
                      style={{ marginRight: '18px' }}
                      onClick={this.saveOrUpdate}
                    >
                      <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
                    </Button>
                    <Button
                      style={{ marginRight: '18px' }}
                      onClick={() => {
                        this.editForm.props.form.resetFields();
                        this.setState({ showList: 1 });
                      }}
                    >
                      <FormattedMessage id="ours.curd.add.back" defaultMessage="返回" />
                    </Button>
                  </React.Fragment>
                </div>,
              ]}
              style={{ ...this.vShow(2) }}
              bodyStyle={{ padding: '20px' }}
              ref={node => {
                this.container = node;
              }}
            >
              <EditForm
                type={this.state.editModalType}
                model={this.state.editModel}
                sourceList={this.state.sourceList}
                loadingCallback={loading => {
                  if (this.state.editModelConfirmLoading !== loading) {
                    this.setState({
                      editModelConfirmLoading: loading,
                    });
                  }
                }}
                wrappedComponentRef={inst => {
                  this.editForm = inst;
                }}
              />
            </Card>
          )}
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default HomeNavi;

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
    loadingCallback: PropTypes.func,
    sourceList: PropTypes.object,
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
    loadingCallback: () => {},
    sourceList: [],
  };

  constructor(props) {
    super(props);
    const defaultFileList = this.props.model.icon
      ? [
          {
            uid: '1',
            name: '',
            status: 'done',
            url: this.props.model.icon,
            type: 'image/',
          },
        ]
      : null; //defaultFileList

    this.state = {
      currentTypeVal: `${this.props.model.type}`,
      previewVisible: false, //上传文件预览
      previewImage: '', //上传文件预览
      defaultFileList, //上传文件列表
      fileList: defaultFileList && defaultFileList.length > 0 ? [defaultFileList[0]] : [],
    };
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {}

  componentDidMount() {
    this.getObjectData(`${this.props.model.type}`);
  }

  handleUploadPreview = file => {
    const previewImage = file.url || file.thumbUrl;
    const previewVisible = file.type.startsWith('image/');
    this.setState({
      previewImage,
      previewVisible,
    });
  };

  handleUploadOnChange = info => {
    const { loadingCallback } = this.props;
    // 状态有：uploading done error removed
    if (info.file.status === 'done') {
      //这个Upload组件比较特殊，这里在OnChange方法手工设置value,不做延迟，就设置不了被覆盖了。
      const response = info.fileList[0].response;
      this.setState({
        fileList: info.fileList,
      });
      if (response) {
        if (response.code === 0) {
          uiUtils.showMessage(`${info.file.name} 文件上传成功.`, 'success');
          setTimeout(() => {
            this.props.form.setFieldsValue({
              icon: response.object,
            });
            if (loadingCallback) {
              loadingCallback(false);
            }
          }, 500);
        } else {
          uiUtils.showAlert(response.msg, 'error');
          if (loadingCallback) {
            loadingCallback(false);
          }
        }
      }
    } else if (info.file.status === 'error') {
      if (loadingCallback) {
        loadingCallback(false);
      }
      uiUtils.showMessage(`${info.file.name} 文件上传失败.`, 'error');
    } else if (info.file.status === 'uploading') {
      if (loadingCallback) {
        loadingCallback(true);
      }
    }
  };

  handleUploadOnRemove = file => {
    //只上传一文件，这里偷懒
    this.setState({
      fileList: [],
      defaultFileList: null,
    });
  };

  beforeUpload = file => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      message.error('只能上传JPG和PNG文件');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('文件不能大于2MB哦!');
      return false;
    }
    return true;
  };

  /**
   * 活动下拉列表数据
   */
  getObjectData = type => {
    // const currentType = this.state.currentTypeVal;
    const currentType = type;
    if (currentType === undefined || currentType === null) {
      return;
    }
    if (currentType === '1') {
      //普通订单、商品
      this.handleSearch();
    } else if (currentType === '2') {
      //专题活动
      this.handleTopicSearch();
    } else if (currentType === '3') {
      //推荐有礼
      this.handleRecommendSearch();
    }
  };

  /**
   * 搜索商品
   * @param value
   */
  handleSearch = value => {
    requestPromise(
      `${getWebPath(`/mailproduct/list?status=2&productName=${value === undefined ? '' : value}`)}`,
      {
        method: 'GET',
      }
    ).then(res => {
      if (res && res.code === 0) {
        const datas = res.page.list || [];
        const results = [
          <Option key="" value="">
            请选择
          </Option>,
        ];
        datas.forEach((r, index) => {
          results.push(
            <Option key={r.id} value={r.id}>
              {r.productName}
            </Option>
          );
        });
        this.setState({
          objectInfo: results,
        });
      }
    });
  };

  /**
   * 搜索专题活动
   * @param value
   */
  handleTopicSearch = value => {
    requestPromise(
      `${getWebPath(
        `/promotiontopic/list?status=1&topicName=${value === undefined ? '' : value}`
      )}`,
      {
        method: 'GET',
      }
    ).then(res => {
      if (res && res.code === 0) {
        const datas = res.page.list || [];
        const results = [
          <Option key="" value="">
            请选择
          </Option>,
        ];
        datas.forEach((r, index) => {
          results.push(
            <Option key={r.topicId} value={r.topicId}>
              {r.topicName}
            </Option>
          );
        });
        this.setState({
          objectInfo: results,
        });
      }
    });
  };

  /**
   * 搜索推荐有礼
   * @param value
   */
  handleRecommendSearch = value => {
    requestPromise(
      `${getWebPath(
        `/promotionrecommend/list/?status=1&topicName=${value === undefined ? '' : value}`
      )}`,
      {
        method: 'GET',
      }
    ).then(res => {
      if (res && res.code === 0) {
        const datas = res.page.list || [];
        const results = [
          <Option key="" value="">
            请选择
          </Option>,
        ];
        /*results.push(
          <Option key={r.recommendId} value={r.recommendId}>
            {r.recommendName}
          </Option>
        );*/
        datas.forEach((r, index) => {
          results.push(
            <Option key={r.recommendId} value={r.recommendId}>
              {r.recommendName}
            </Option>
          );
        });
        this.setState({
          objectInfo: results,
        });
      }
    });
  };

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );

    const typeRoles =
      type === 'add'
        ? [
            {
              required: true,
              message: '类型必填',
            },
            // rulesRemote('POST', getWebPath('/bushomenavi/checkHomeNaviExist')),
          ]
        : [];

    const uploadProps = {
      // name: 'file',
      // action: '//jsonplaceholder.typicode.com/posts/',
      action: `${getWebPath('/api/fileUpload')}`,
      name: 'myfile',
      data: { moduleName: 'homenavi', isImage: true, acceptFileExts: 'image' },
      withCredentials: true,
      headers: {
        authorization: 'authorization-text',
      },
      onChange: this.handleUploadOnChange,
      onRemove: this.handleUploadOnRemove,
      defaultFileList: this.state.defaultFileList,
      multiple: false,
      accept: '.jpg, .jpeg, .png', //image/*
    };

    const imageUrl = this.state.imageUrl;

    const sourceTypeList = this.props.sourceList || [];
    let sourceType = new Map();
    sourceTypeList.forEach(value => {
      if (value !== undefined && value.id !== '') {
        sourceType.set(Number.parseFloat(value.id), value.name);
      }
    });

    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Form layout="horizontal">
        <Row gutter={{ ...rowGutterPxLayout }}>
          <Col {...colSpanLayout}>
            <FormItem label="活动类型" {...formItemLayout}>
              {type === 'view'
                ? sourceType.get(model.type)
                : getFieldDecorator('type', {
                    initialValue: `${model.type}`,
                    rules: [
                      {
                        required: true,
                        message: '类型必填',
                      },
                      // rulesRemote('POST', getWebPath('/bushomenavi/checkHomeNaviExist')),
                    ],
                  })(
                    <Select
                      style={{ width: '100%' }}
                      placeholder="类型"
                      onChange={value => {
                        // console.log(this.props.model.type);
                        console.log(value);
                        this.state.currentTypeVal = value;
                        this.getObjectData(value);
                        console.log('加载下拉列表数据');
                      }}
                      {...inputCodeDisabled}
                    >
                      {uiUtils.getOptionList(this.props.sourceList)}
                    </Select>
                  )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="活动名称" {...formItemLayout}>
              {type === 'view'
                ? model.name
                : getFieldDecorator('name', {
                    initialValue: model.name,
                    rules: [
                      {
                        required: true,
                        message: '名称必填',
                      },
                      {
                        whitespace: true,
                        message: '不能包含空白符',
                      },
                      {
                        max: 15,
                        message: '最长15个字符',
                      },
                    ],
                  })(<Input type="text" autocomplete="off" maxlength={15} placeholder="名称" />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="活动标题" {...formItemLayout}>
              {type === 'view'
                ? model.title
                : getFieldDecorator('title', {
                    initialValue: model.title,
                    rules: [
                      {
                        required: true,
                        message: '标题必填',
                      },
                      {
                        whitespace: true,
                        message: '不能包含空白符',
                      },
                      {
                        max: 15,
                        message: '最长15个字符',
                      },
                    ],
                  })(<Input type="text" autocomplete="off" maxlength={15} placeholder="标题" />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="活动描述" {...formItemLayout}>
              {type === 'view'
                ? model.description
                : getFieldDecorator('description', {
                    initialValue: model.description,
                  })(
                    <TextArea
                      autosize={{ minRows: 3, maxRows: 6 }}
                      maxlength={100}
                      placeholder="活动描述"
                    />
                  )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem
              label="图标"
              extra={type === 'view' ? '' : '支持png、jpg、gif, 大小不超过3MB, 推荐尺寸：332X270'}
              {...formItemLayout}
            >
              {type === 'view' ? (
                <DefaultImage src={model.icon} alt="" width="100px" height="97px" />
              ) : (
                getFieldDecorator('icon', {
                  initialValue: model.icon,
                })(
                  <div className="clearfix">
                    <Upload
                      {...uploadProps}
                      listType="picture-card"
                      onPreview={this.handleUploadPreview}
                    >
                      {this.state.fileList && this.state.fileList.length >= 1 ? null : uploadButton}
                    </Upload>
                    <Modal
                      visible={this.state.previewVisible}
                      footer={null}
                      onCancel={() => this.setState({ previewVisible: false })}
                    >
                      <img
                        alt="imgExample"
                        style={{ width: '100%' }}
                        src={this.state.previewImage}
                      />
                    </Modal>
                  </div>
                )
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="背景色值" {...formItemLayout}>
              {type === 'view'
                ? model.bugColor
                : getFieldDecorator('bugColor', {
                    initialValue: model.bugColor,
                    rules: [],
                  })(<InputColor initialHexColor={model.bugColor} placement="right" />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="排序" {...formItemLayout}>
              {type === 'view'
                ? model.sort
                : getFieldDecorator('sort', {
                    initialValue: model.sort,
                    rules: [
                      {
                        required: true,
                        message: '排序必填',
                      },
                      // rulesReg('number'),
                    ],
                  })(
                    <InputNumber
                      placeholder="排序"
                      min={0}
                      max={999999999}
                      style={{ width: 100 }}
                    />
                  )}
              {type === 'view' ? (
                ''
              ) : (
                <Tooltip placement="right" title="排序默认为从小到大(升序)">
                  <Icon type="question-circle" />
                </Tooltip>
              )}
            </FormItem>
          </Col>
        </Row>

        {(this.state.currentTypeVal === '1' ||
          this.state.currentTypeVal === '2' ||
          this.state.currentTypeVal === '3') && (
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <FormItem
                label="目标数据"
                {...formItemLayout}
                extra={
                  type !== 'view'
                    ? '根据活动类型来区分：专题活动：选择一个专题活动，推荐有礼：选择一个推荐有礼的活动，普通订单/普通商品：选择一个商品'
                    : ''
                }
              >
                {type === 'view'
                  ? model.objectName
                  : getFieldDecorator('objectId', {
                      initialValue: model.objectId,
                      rules: [
                        {
                          required: true,
                          message: '必填',
                        },
                      ],
                    })(
                      <Select
                        showSearch
                        style={{ width: '100%' }}
                        onSearch={value => {
                          const currentType = this.state.currentTypeVal;
                          if (currentType === undefined || currentType === null) {
                            return;
                          }
                          if (currentType === '1') {
                            //普通订单、商品
                            this.handleSearch(value);
                          } else if (currentType === '2') {
                            //专题活动
                            this.handleTopicSearch(value);
                          } else if (currentType === '3') {
                            //推荐有礼
                            this.handleRecommendSearch(value);
                          }
                        }}
                        optionFilterProp="children"
                        notFoundContent={null}
                        placeholder="请选择目标数据"
                      >
                        {this.state.objectInfo}
                      </Select>
                    )}
              </FormItem>
            </Col>
          </Row>
        )}
      </Form>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
